<?php

namespace Home\Logic;
class WxloginLogic{
    
    private $wxappId;
    private $secret;
    public function __construct(){
        $this->wxappId = C("WX_APPID");
        $this->secret = C('WX_APPSECRET');
    }
    
    /**
     * 微信登录执行方法
     * $redirectUrl为登录成功后返回方法，默认为主页
     * 登录成功的方法必须执行此类的 login_success方法
     * @param string $redirectUrl
     * @return boolean
     */
    public function login($redirectUrl = null){
        $appid = $this->wxappId;
        if($redirectUrl==null){
            $redirectUrl = 'https://babyvideo.zhfancon.com/index/getUserInfo';
        }
        $redirectUrl = urlencode($redirectUrl);
        $wxLoginUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirectUrl."&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
        
        redirect($wxLoginUrl);
        
    }
    
    public function getAccessToken(){
        $appid = $this->wxappId;
        $appsecret = $this->secret;
        //第一步：获取全局access_token
        $getUserOpenidUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;
        $token = $this->wxCurlPost($getUserOpenidUrl);
        cookie('wx_access_token',$token["access_token"],7000);
        
        return $token;
    }
    
    public function wxCurlPost($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode($output, true);
    }
}

?>